/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.main.controller;

import com.kimstore.bean.Item;
import com.kimstore.bean.ItemStatus;
import com.kimstore.bean.Order;
import com.kimstore.bean.Staff;
import com.kimstore.factory.DaoFactory;
import com.kimstore.gui.main.Inventory;
import com.kimstore.gui.sales.NewOrderController;
import com.kimstore.gui.sales.ViewUpdateOrderController;
import com.kimstore.utilities.CustomTableRowSorter;
import com.kimstore.utilities.DateUtil;
import com.kimstore.utilities.PaginateSearchAndFilter;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.HighlighterFactory;

/**
 *
 * @author Administrator
 */
public class OrdersTabController extends BaseTabController {

    public Inventory parentController;
    public JComboBox staffFilterComboBox;
    private PaginateSearchAndFilter<Order> psaf;

    public OrdersTabController(Inventory parentController) {
        this.parentController = parentController;
        //queryElements = new QueryElements("Order", "order");
    }

    public void createNewOrderWindow() {
        NewOrderController newOrderController = new NewOrderController(this);
        newOrderController.displayWindow();
    }

    public void createNewOrderWindowCallback(Order order) {
        refreshTable();

        parentController.getInventoryTabController().refreshTable();
        parentController.getCustomerTabController().refreshTable();
        parentController.getStaffTabController().refreshTable();
    }

    public void refreshTable() {
        clearTable();
        populateOrdersTable();
    }

    public void populateOrdersTable() {
        populateOrdersTable(psaf.search());
        /*
         DefaultTableModel model = (DefaultTableModel) table.getModel();
         List<Order> orders = DaoFactory.getInstance().getOrderDao().findAll();

         for (Order o : orders) {
         String status = getStatus(o);
         model.insertRow(model.getRowCount(), new Object[]{o.getId(), (o.getStaff() != null) ? o.getStaff().getName() : "", o.getCustomerType(), DateUtil.formatDate(o.getOrderDate(), DateUtil.HUMAN_READABLE_FORMAT), status});
         }
         */
    }

    private String getStatus(Order o) {
        String status = "";
        int count = 0;

        for (Item i : o.getItems()) {
            if (i.getHistory().get(i.getHistory().size() - 1).getType().equals(ItemStatus.DELIVERED)) {
                count++;
            }
        }

        status += ((count == o.getItems().size()) ? "Completed" : "On Going") + " (" + count + "/" + o.getItems().size() + " Delivered)";
        return status;
    }

    public void populateStaffComboBox() {
        List<Staff> staff = DaoFactory.getInstance().getStaffDao().findAll();
        if (staff != null) {
            for (Staff s : staff) {
                staffFilterComboBox.addItem(s);
            }
        }
    }

    public void createViewUpdateOrderWindow(Integer orderId) {
        ViewUpdateOrderController viewUpdateOrderController = new ViewUpdateOrderController(this, orderId);
        viewUpdateOrderController.displayWindow();

    }

    public void clearTable() {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);
    }

    public void setStaffComboBox(JComboBox staffFilterComboBox) {
        this.staffFilterComboBox = staffFilterComboBox;
    }

    public void refreshComboBox() {
        while (staffFilterComboBox.getItemCount() > 1) {
            if (staffFilterComboBox.getItemAt(1) instanceof Staff) {
                staffFilterComboBox.removeItemAt(1);
            }
        }

        populateStaffComboBox();
    }

    @Override
    public void prepareUserInterface() {
        //searchField.setPrompt(searchFieldPromptText);
        table.setShowGrid(true, true);
        table.addHighlighter(HighlighterFactory.createSimpleStriping());
    }

    private void populateOrdersTable(List<Order> orders) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);
        for (Order o : orders) {
            model.insertRow(model.getRowCount(), new Object[]{o.getId(),
                        o.getStaff().getName(),
                        o.getCustomerType(),
                        DateUtil.formatDate(o.getOrderDate(), DateUtil.HUMAN_READABLE_FORMAT),
                        getStatus(o)});
        }
    }

    @Override
    public void bindElements() {
        table.setRowSorter(new CustomTableRowSorter(table.getRowSorter().getModel()) {
            @Override
            public void sort() {
                if (table.isShowing()) {
                    Point p = MouseInfo.getPointerInfo().getLocation();
                    int column = getSelectedColumn(p);
                    if (psaf.isColumnSortable(column)) {
                        populateOrdersTable(psaf.sort(column));
                    }
                }
            }
        });
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                populateOrdersTable(psaf.search());
            }
        });
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<Order> orders = psaf.nextPage();
                if (orders != null) {
                    populateOrdersTable(orders);
                }
            }
        });

        prevButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List<Order> orders = psaf.previousPage();
                if (orders != null) {
                    populateOrdersTable(orders);
                }
            }
        });
    }

    public PaginateSearchAndFilter<Order> getSfap() {
        return psaf;
    }

    public void setPsaf(PaginateSearchAndFilter<Order> sfap) {
        this.psaf = sfap;
    }

    private int getSelectedColumn(Point point) {
        int mousex = point.x - table.getLocationOnScreen().x;
        int mousey = point.y - table.getLocationOnScreen().y;
        Point mousep = new Point(mousex, mousey);

        return table.columnAtPoint(mousep);
    }
}
